from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.contrib.auth.views import login_required
from .models import BookShelf
from main.models import Book


# Create your views here.
@login_required
def collect(request):
    bookshelfs = BookShelf.objects.all()
    return render(request, 'bookshelf/collect.html', context={'bookshelfs': bookshelfs})


def change_collect(request):
    if request.method == "POST":
        books_id = request.POST.get("books_id")
        book = Book.objects.get(id=books_id)
        c = BookShelf.objects.filter(user=request.user, id=book.id).first()
        if c:
            c.delete()
            return JsonResponse({
                "code": 0,
                "msg": "取消收藏成功",
                "data": {
                    "state": False
                }
            })
        else:
            temp = BookShelf()
            temp.user_id = request.user.id
            temp.id = book.id
            temp.author_id = book.author.id
            temp.book_id = book.id
            temp.category_id = book.category.id
            temp.save()
            return JsonResponse({
                "code": 0,
                "msg": "收藏成功",
                "data": {
                    "state": True
                }
            })

    else:
        return JsonResponse({
            "code": -1,
            "msg": "方法不允许"
        })
